package com.wms.uitl;

import java.io.StringWriter;
import java.util.Map;
import javax.annotation.Resource;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Service;
import com.wms.crypt.EncryptAndDEcrypt;

/*
 * 工具类，将map转换成json，并将json进行 rsa  url 两次加密
 */

@Service
public class ConvertMap2Json {
	
	@Resource
	private EncryptAndDEcrypt encryptor;
	
	public void setEncryptor(EncryptAndDEcrypt encryptor) {
		this.encryptor = encryptor;
	}

	private static final ObjectMapper om = new ObjectMapper();//jackson 转换器，将object 转换成json string
	private static StringWriter sw = new StringWriter();//jackson 转换时用到的输出流
	
	//进行rsa url两次加密
	public String convertWithEncrypt(Map<String,String> map) throws Exception{
		
		if(map == null){
			return null;
		}
		
		if(map.size() == 0){
			return null;
		}
		
		convertor(map);
		
		//两次加密，先用公钥加密，在进行url加密
		return java.net.URLEncoder.encode(encryptor.encrypToHex(sw.toString()),"UTF-8");
	}
	
	
	//只进行url加密
	public String convertWithoutEncrypt(Map<String,String> map) throws Exception{
		
		if(map == null){
			return null;
		}
		
		if(map.size() == 0){
			return null;
		}
		
		convertor(map);
		
		//首次传输密钥，只用url加密
		return java.net.URLEncoder.encode(sw.toString(),"UTF-8");
	}
	
	
	private void convertor(Map<String,String> map)throws Exception{
		
		try{
			om.writeValue(sw, map);//进行转换
			
			sw.flush();
			sw.close();//关闭输出流
		}catch (Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}finally{
			sw.close();
		}
	}
	

}
